package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.EditActivity;
import jp.co.sharp.android.parents.kidsguard.activity.edit.GpsSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.SettingAdapter;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

/**
 * キッズケータイの設定
 */
public class SettingActivity extends Activity {

    private App mApp;
    private String[] mStrSettingItem = new String[]{"クイック発信", "防犯ブザー", "イマドコサーチ", "電池残量通知", "おかえり通知", "電源オフ", "権限付与"};
    // 選択済み
    private KidInfoEntity mKidInfoEntity;
    private boolean mUnReceiver = true;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(this.TAG, "SettingActivity_onCreate");
        setContentView(R.layout.activity_setting);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(this.TAG, "SettingActivity_onStart");
        synchronized (mSyncLock) {
            initActivity();
            initReceiver();
            mApp.setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(this.TAG, "SettingActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(this.TAG, "SettingActivity_onDestroy");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(this.TAG, "SettingActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        registerReceiver(systemReceiver, filter);
        mUnReceiver = false;
    }

    /**
     *
     */
    private void initActivity() {
        Log.i(this.TAG, "SettingActivity_initActivity");
        mApp = (App)getApplication();
        mKidInfoEntity = mApp.findKidInfoBySelect();

        TextView textView = (TextView)findViewById(R.id.settingSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);

        ListView settingListView = (ListView)findViewById(R.id.settingListView);
        SettingAdapter settingAdapter =
                new SettingAdapter(SettingActivity.this, R.layout.activity_setting_item, mStrSettingItem);
        settingListView.setAdapter(settingAdapter);

        settingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (checkBluetoothState()) {
                    if (checkKidState()) {
                        // ページジャンプ
                        mPageJumpFlag = true;
                        switch(i){
                            case 0:
                                quickMail();
                                break;
                            case 1:
                                alarmSettings();
                                break;
                            case 2:
                                gpsSetting();
                                break;
                            case 3:
                                powerInfo();
                                break;
                            case 4:
                                toInform();
                                break;
                            case 5:
                                setPower();
                                break;
                            case 6:
                                giveAuthority();
                                break;
                        }
                    } else {
                        String message = mKidInfoEntity.getKidName() + "に接続できませんでした。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(SettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                } else {
                    OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(SettingActivity.this, R.style.commonDlg);
                    openBluetoothConfirmDlg.show();
                    openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            openBluetoothConfirmDlg.dismiss();
                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                        }
                    });
                }
            }
        });
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        // ブロードキャストの再登録
                        unregisterReceiver(systemReceiver);
                        initReceiver();
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // Bluetoothステータス監視
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);

                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(SettingActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * KidInfo Status Check
     * @return true:连接  false:手动断开
     */
    private boolean checkKidState() {
        Log.i(this.TAG, "SettingActivity_checkKidState");
        String kidStatus = mApp.findKidInfoBySelect().getBtConnStatus();
        if (Constants.DEVICE_CONNECTION_SUCCESS.equals(kidStatus)) {
            return true;
        }
        return false;
    }

    /**
     * bluetooth status
     * @return true: Open  false: Close
     */
    private boolean checkBluetoothState() {
        Log.i(this.TAG, "SettingActivity_checkBluetoothState");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (bluetoothAdapter.isEnabled()) {
                return true;
            }
        }
        return false;
    }

    /**
     * パージクイック発信
     */
    public void quickMail() {
        Log.i(this.TAG, "SettingActivity_quickMail");
        Intent intent = new Intent(SettingActivity.this,QuickDispatchSettingActivity.class);
        startActivity(intent);
    }
    /**
     * パージ防犯ブザー
     */
    public void alarmSettings() {
        Log.i(this.TAG, "SettingActivity_alarmSettings");
        Intent intent = new Intent(SettingActivity.this,PersonalAlarmSettingActivity.class);
        startActivity(intent);
    }
    /**
     * パージイマドコサーチ
     */
    public void gpsSetting() {
        Log.i(this.TAG, "SettingActivity_gpsSetting");
        Intent intent = new Intent(SettingActivity.this, GpsSettingActivity.class);
        startActivity(intent);
    }
    /**
     * パージ電池残量通知
     */
    public void powerInfo() {
        Log.i(this.TAG, "SettingActivity_powerInfo");
        Intent intent = new Intent(SettingActivity.this,BatterySurplusSettingActivity.class);
        startActivity(intent);
    }
    /**
     * パージおかえり通知
     */
    public void toInform() {
        Log.i(this.TAG, "SettingActivity_toInform");
        Intent intent = new Intent(SettingActivity.this,OkaeriNotificationActivity.class);
        startActivity(intent);

    }
    /**
     * パージ電源オフ
     */
    public void setPower() {
        Log.i(this.TAG, "SettingActivity_setPower");
        Intent intent = new Intent();
        intent.setClass(SettingActivity.this, PowerSettingActivity.class);
        startActivity(intent);
    }
    /**
     * パージ権限付与
     */
    public void giveAuthority() {
        Log.i(this.TAG, "SettingActivity_giveAuthority");
        Intent intent = new Intent();
        intent.setClass(SettingActivity.this, AuthorityActivity.class);
        startActivity(intent);
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }
    /**
     *
     */
    public void backActivity(View view) {
        Log.i(this.TAG, "SettingActivity_backActivity");
        Intent intent = new Intent();
        intent.setClass(SettingActivity.this, HomeActivity.class);
        startActivity(intent);
    }
}
